//
//  HTNetworking.m
//  CreditCommunity
//
//  Created by maiya on 2017/10/12.
//  Copyright © 2017年 maiya. All rights reserved.
//

#import "HTNetworking.h"

@interface HTNetworking ()
// 临时，暂时保存每个业务请求
@property (nonatomic, copy) NSMutableArray *apiTools;

@end

@implementation HTNetworking

#pragma mark - 单利
+ (instancetype)sharedManager {
    
    static HTNetworking *_instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self manager];
        _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    });
    return _instance;
}

#pragma mark - 添加对象
- (void)addAPITool:(id)object {
    if (nil == object) {
        return;
    }
    if (nil == _apiTools) {
        _apiTools = [[NSMutableArray alloc] init];
    }
    
    [_apiTools addObject:object];
}

#pragma mark - 删除对象
- (void)removeAPITool:(id)object {
    [_apiTools removeObject:object];
}


#pragma mark - 网络状态
- (AFNetworkReachabilityStatus)networkReachabilityStatus {
    return [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
}

#pragma mark - POST网络请求
- (void)POST:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock netError:(NetErrorBlock)netErrorBlock {
    
    [self POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求成回调
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //失败回调
        if (failureBlock) {
            failureBlock(error);
        }

        //是否网络不可用
        if ([self networkReachabilityStatus] == AFNetworkReachabilityStatusNotReachable) {
            if (netErrorBlock) {
                netErrorBlock(@"未检测到网络");
            }
        }
  
    }];
    
}


#pragma mark - GET 网络请求
- (void)GET:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock netError:(NetErrorBlock)netErrorBlock {
    
    [self GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求成回调
        if (_successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //失败回调
        if (_failureBlock) {
            failureBlock(error);
        }
        
        //是否网络不可用
        if ([self networkReachabilityStatus] == AFNetworkReachabilityStatusNotReachable) {
            if (_netErrorBlock) {
                netErrorBlock(@"未检测到网络");
            }
        }
        
    }];
    
}
@end
